#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SMS via MultiTech SMS-Gateway

# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Send SMS via MultiTech SMS-Gateway # encoding: utf-8
#
# This notification script can be put below share/check_mk/notifications. It sends
# SMS via a MultiTech SMS-Gateway
# (http://www.multitech.com/en_US/PRODUCTS/Families/MultiModemiSMS/)
# Please add your personal configuration directly in this
# script. The target phone number is take from the contact's pager address.
# You can override this by specifying it as a parameter
#
# Some hints for setup of the MultiTech SMS-Gateway:
#
# * Please use at least Firmware Version 1.51.9 earlier versions did cause much
#   trouble. The devices are not yet delivered with this version, so an upgrade is
#   required. You get SF100-u-v1.51.9-16Jan2013.bin.zip e. g. at
#   https://shop.netways.de/attachment.php?id_attachment=64
#
# * Deactivate the PIN of the SIM card. This can be done most easy by inserting
#   the SIM into a mobile phone.
#
# * By default, the device has IP 192.168.2.1, user admin, password admin.
#   You can change these in the admin interface by browser (http).
#
# * Look into the status information in the web interface to make sure, the
#   SIM card is displayed as enabled there.
#   If not: Make sure you did insert the SIM card with contacts to the bottom,
#   and the cut off corner to the front right.
#
# * Under
#     Administration > Admin Access > Allowed Networks
#   you can restrict access to the device. Make sure, the IPs of the sending
#   Checkmk machines are included there.
#
# * Under
#     SMS Services > Send API
#   enable HTTP Status, set port to 80
#
# * Under
#     SMS Services > International Number
#   clear the check box "Disable International Number"
#
# * Under
#     SMS Services > Send SMS Users
#   create a user for Checkmk. This one needs to be entered below.
#   Make sure you choose a password, which is not longer than 8 characters.
#   On the device it is possible to set a longer password, but authentication
#   with it is impossible!! :-(
#
# * Do not forget to go to the "Save & Restart" tab and click "save" there.
#   This writes your changes into the flash memory of the device. Otherwise
#   they will be lost on next reboot.
#

import sys, os, urllib

# This does not need to be changed
to = os.environ.get("NOTIFY_CONTACTPAGER")
fromname = "Check_MK"
user = "nagios"
passwd = "test123"
url = "http://isms.example.com/sendmsg?"

if len(sys.argv) > 1:
    to = sys.argv[1]

if not to:
    sys.stderr.write("NOTIFY_CONTACTPAGER is not set.\n")
    sys.exit(1)

max_len = 160
message = os.environ['NOTIFY_HOSTNAME'] + " "

if os.environ['NOTIFY_WHAT'] == 'SERVICE':
    message += os.environ['NOTIFY_SERVICESTATE'][:2] + " "
    avail_len = max_len - len(message)
    message += os.environ['NOTIFY_SERVICEDESC'][:avail_len] + " "
    avail_len = max_len - len(message)
    message += os.environ['NOTIFY_SERVICEOUTPUT'][:avail_len]

else:
    message += "is " + os.environ['NOTIFY_HOSTSTATE']

# constructing a url like
# http://isms.example.com/sendmsg?user=nagios&passwd=test123&cat=1&to=017012345678&text=sample'
url += urllib.urlencode([("user", user), ("passwd", passwd), ("cat", "1"), ("to", to),
                         ("text", message)])

try:
    handle = urllib.urlopen(url)
    response = handle.read().strip()
    sys.stdout.write("%s\n" % response)
    if response.startswith("ID:"):
        sys.stdout.write("Successfully sent SMS to %s\n" % to)
    else:
        sys.stderr.write("Error sending SMS to %s: %s\n" % (to, response))
        sys.stderr.write("URL was %s\n" % url)
except Exception as e:
    sys.stderr.write("Error sending SMS to %s. Exception: %s%s\n" % e)
